# python3.7
# -*- coding: utf-8 -*-
# @Time     : 2023/2/25
# @Author   :
# @File     : qidianCode.py
# @function : 爬取起点中文网排行榜
# @Software : PyCharm Community Edition
# @Knowledge: requests、BeautifulSoup、写文件
from bs4 import BeautifulSoup
import requests
import xlwt


datas = []

# 将数据写入文件
def save_file(fileName):

    wb=xlwt.Workbook()
    ws=wb.add_sheet("Sheet1")
    #write headers
    ws.write(0,0,"序号")
    ws.write(0, 1, "小说名")
    ws.write(0, 2, "类型")
    ws.write(0, 3, "简介")
    ws.write(0, 4, "更新情况")
    #write content
    for idx,book in enumerate(datas,start=1):
        ws.write(idx,0,idx)
        ws.write(idx,1,book[0][0])
        ws.write(idx, 2, book[0][1])
        ws.write(idx, 3, book[0][2])
        ws.write(idx, 4, book[0][3])



    wb.save(fileName)
# 获得数据存入datas列表
def gain_data(url):
    response=requests.get(url)

    if response.status_code==200:
        content=BeautifulSoup(response.content,features="lxml")

        for book in content.find_all("div",class_="book-mid-info"):
            onebook = []
            title=book.h2.a.get_text()
            type=book.find("p",class_="author").span.get_text(strip=True)
            intro=book.find("p",class_="intro").get_text(strip=True)
            update=book.find("p",class_="update").get_text(strip=True)

            onebook.append([title,type,intro,update])
            datas.append(onebook)


    else:
        print("Error url: {response.status_code}")
    # 在控制台输出数据
def show_data():
    for idx,book in enumerate(datas,start=1):
        print(f"{idx},{','.join(book[0])}")

    # 主程序
if __name__ == "__main__":
    # 网址列表
    urllist = ['http://localhost:8080/qidian/yuepiao.html',
               'http://localhost:8080/qidian/hotsales.html',
               'http://localhost:8080/qidian/readindex.html',
               'http://localhost:8080/qidian/newfans.html',
               'http://localhost:8080/qidian/recom.html',
               'http://localhost:8080/qidian/collect.html',
               'http://localhost:8080/qidian/vipup.html',
               'http://localhost:8080/qidian/vipcollect.html']

    choicesList = ["1.月票榜", " 2.畅销榜", "3.阅读指数榜", "4.书友榜", "5.推荐榜", "6.收藏榜", "7.更新榜", "8.VIP收藏榜"]
    print(choicesList)
    choice = int(input('请选择你想查看的榜单:'))
    url = urllist[choice - 1]
    gain_data(url)
    show_data()
    save_file(choicesList[choice - 1] + ".xls")
